package com.jielihaofeng.nettyadvance.chat.server.handler;

import com.jielihaofeng.nettyadvance.chat.message.ChatRequestMessage;
import com.jielihaofeng.nettyadvance.chat.message.ChatResponseMessage;
import com.jielihaofeng.nettyadvance.chat.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Johnnie Wind
 * @description 聊天消息处理器
 * @date 2021/11/18 14:42
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage message) throws Exception {
        String from = message.getFrom();
        String to = message.getTo();
        String content = message.getContent();
        // 获取对应用户的channel
        Channel channel = SessionFactory.getSession().getChannel(to);
        // 在线
        if (channel != null) {
            channel.writeAndFlush(new ChatResponseMessage(from, content));
        }
        // 不在线
        else {
            ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或不在线"));
        }
    }
}
